import {
  authModel
} from '../../models/auth';
import {
  positionListModel
} from '../../models/positions';
import positionsTpl from '../../views/positions.art';
import positionsListTpl from '../../views/positions-list.art';
import {
  addPosition
} from './add-position';
import {
  updatePosition,
  fillPositionsUpdateTpl
} from './update-position';

import pagination from '../../components/pagination';
import page from '../../databus/page';
import {
  remove
} from '../common/index';

const pageSize = page.pageSize;
// let dataList = [];

//数据
let state = {
  list: []
};

//订阅模式
const _subscribe = () => {
  $('body').off('changeCurrentPage').on('changeCurrentPage', (e, index) => {
    _list(index);
  });
  $('body').off('addPosition').on('addPosition', (e) => {
    _loadData();
  });
}

//请求用户列表数据 传入页码数字
const _list = (pageNo) => {
  //渲染list
  $('#positions-list').html(positionsListTpl({
    data: state.list.slice((pageNo - 1) * pageSize, pageNo * pageSize)
  }));
}

//请求数据库数据并存入临时数据dataList 并渲染数据
const _loadData = async () => {
  const list = await positionListModel();
  state.list = list;
  //实现分页 此处应该放公共参数
  pagination(list, pageSize, page.currentPage);
  //数据渲染
  _list(page.currentPage);
}

const listPositions = (router) => {
  return async (req, res, next) => {
    let result = await authModel();
    if (result.ret) {
      next();
      res.render(positionsTpl());

      //获取用户列表数据
      _loadData();

      //订阅事件
      _subscribe();

      //添加职位
      addPosition();

      //删除职位
      remove({
        $box: $('#positions-list'),
        state, //传递一个引用类型的值stata
        // dataList,
        url: 'api/positions/remove',
        loadData: _loadData
      })


      updatePosition();

      $('#positions-list')
        .off('click', '.positions-update')
        .on('click', '.positions-update', function () {
          //编辑职位
          fillPositionsUpdateTpl($(this).data('id'));
        })

    } else {
      router.go('/signin');
    }
  }
}

export default listPositions